from flask_sqlalchemy import SQLAlchemy
from flask_jwt_extended import create_access_token
from werkzeug.security import generate_password_hash, check_password_hash
from datetime import datetime
import json

db = SQLAlchemy()

class User(db.Model):
    """用户模型"""
    __tablename__ = 'users'
    
    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(80), unique=True, nullable=False)
    password_hash = db.Column(db.String(255), nullable=False)
    role = db.Column(db.String(100), nullable=False)
    created_at = db.Column(db.DateTime, default=datetime.utcnow)
    last_login = db.Column(db.DateTime)
    
    def set_password(self, password):
        """设置密码哈希"""
        self.password_hash = generate_password_hash(password)
    
    def check_password(self, password):
        """验证密码"""
        return check_password_hash(self.password_hash, password)
    
    def to_dict(self):
        """转换为字典"""
        return {
            'id': self.id,
            'username': self.username,
            'role': self.role,
            'created_at': self.created_at.isoformat() if self.created_at else None,
            'last_login': self.last_login.isoformat() if self.last_login else None
        }

class Intersection(db.Model):
    """路口数据模型"""
    __tablename__ = 'intersections'
    
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(200), nullable=False)
    type = db.Column(db.String(100), nullable=False)
    location = db.Column(db.String(500), nullable=False)
    lane_count = db.Column(db.Integer)
    signal_config = db.Column(db.Text)
    peak_hours = db.Column(db.String(200))
    avg_traffic = db.Column(db.String(200))
    accident_records = db.Column(db.Text)
    surrounding_facilities = db.Column(db.Text)
    created_at = db.Column(db.DateTime, default=datetime.utcnow)
    updated_at = db.Column(db.DateTime, default=datetime.utcnow, onupdate=datetime.utcnow)
    
    def to_dict(self):
        """转换为字典"""
        return {
            'id': self.id,
            'name': self.name,
            'type': self.type,
            'location': self.location,
            'lane_count': self.lane_count,
            'signal_config': self.signal_config,
            'peak_hours': self.peak_hours,
            'avg_traffic': self.avg_traffic,
            'accident_records': self.accident_records,
            'surrounding_facilities': self.surrounding_facilities,
            'created_at': self.created_at.isoformat() if self.created_at else None,
            'updated_at': self.updated_at.isoformat() if self.updated_at else None
        }

class OptimizationRecord(db.Model):
    """优化记录模型"""
    __tablename__ = 'optimization_records'
    
    id = db.Column(db.Integer, primary_key=True)
    optimize_date = db.Column(db.Date)
    optimizer = db.Column(db.String(100), nullable=False)
    content = db.Column(db.Text, nullable=False)
    effect = db.Column(db.Text)
    before_data = db.Column(db.Text)  # JSON格式存储
    after_data = db.Column(db.Text)   # JSON格式存储
    created_at = db.Column(db.DateTime, default=datetime.utcnow)
    updated_at = db.Column(db.DateTime, default=datetime.utcnow, onupdate=datetime.utcnow)
    
    def to_dict(self):
        """转换为字典"""
        return {
            'id': self.id,
            'optimize_date': self.optimize_date.isoformat() if self.optimize_date else None,
            'optimizer': self.optimizer,
            'content': self.content,
            'effect': self.effect,
            'before_data': json.loads(self.before_data) if self.before_data else None,
            'after_data': json.loads(self.after_data) if self.after_data else None,
            'created_at': self.created_at.isoformat() if self.created_at else None,
            'updated_at': self.updated_at.isoformat() if self.updated_at else None
        }

class AIAnalysis(db.Model):
    """AI分析模型"""
    __tablename__ = 'ai_analyses'
    
    id = db.Column(db.Integer, primary_key=True)
    intersection_id = db.Column(db.Integer)
    intersection_name = db.Column(db.String(200), nullable=False)
    period = db.Column(db.String(100))
    goals = db.Column(db.Text)  # JSON格式存储
    result_summary = db.Column(db.Text)
    problems = db.Column(db.Text)  # JSON格式存储
    suggestions = db.Column(db.Text)  # JSON格式存储
    expected_effects = db.Column(db.Text)  # JSON格式存储
    confidence_score = db.Column(db.Float)
    analysis_time = db.Column(db.Integer)  # 分析耗时（秒）
    created_at = db.Column(db.DateTime, default=datetime.utcnow)
    updated_at = db.Column(db.DateTime, default=datetime.utcnow, onupdate=datetime.utcnow)
    
    def to_dict(self):
        """转换为字典"""
        return {
            'id': self.id,
            'intersection_id': self.intersection_id,
            'intersection_name': self.intersection_name,
            'period': self.period,
            'result_summary': self.result_summary,
            'confidence_score': self.confidence_score,
            'analysis_time': self.analysis_time,
            'created_at': self.created_at.isoformat() if self.created_at else None,
            'updated_at': self.updated_at.isoformat() if self.updated_at else None,
            'goals': json.loads(self.goals) if self.goals else None,
            'problems': json.loads(self.problems) if self.problems else None,
            'suggestions': json.loads(self.suggestions) if self.suggestions else None,
            'expected_effects': json.loads(self.expected_effects) if self.expected_effects else None
        }

class SystemLog(db.Model):
    """系统日志模型"""
    __tablename__ = 'system_logs'
    
    id = db.Column(db.Integer, primary_key=True)
    level = db.Column(db.String(20), nullable=False)  # INFO, WARNING, ERROR等
    module = db.Column(db.String(100))  # 日志来源模块
    message = db.Column(db.Text, nullable=False)
    user = db.Column(db.String(100))  # 操作用户
    timestamp = db.Column(db.DateTime, default=datetime.utcnow)
    
    def to_dict(self):
        """转换为字典"""
        return {
            'id': self.id,
            'level': self.level,
            'module': self.module,
            'message': self.message,
            'user': self.user,
            'timestamp': self.timestamp.isoformat() if self.timestamp else None
        }

class SystemSetting(db.Model):
    """系统设置模型"""
    __tablename__ = 'system_settings'
    
    id = db.Column(db.Integer, primary_key=True)
    key = db.Column(db.String(100), unique=True, nullable=False)
    value = db.Column(db.Text, nullable=False)
    description = db.Column(db.String(500))
    
    def to_dict(self):
        """转换为字典"""
        return {
            'id': self.id,
            'key': self.key,
            'value': self.value,
            'description': self.description
        }